<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="600px"
    @close="closeDialog"
  >
    <el-form ref="formRef" label-width="120px" :model="form" :rules="rules">
      <el-form-item label="单位编码" prop="measCode">
        <el-input v-model.trim="form.measCode" />
      </el-form-item>
      <el-form-item label="单位名称" prop="measName">
        <el-input v-model.trim="form.measName" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
  import { ref } from 'vue'
  import { addMeasdocApi, updateMeasdocApi } from '@/api/base/measdoc'
  import { localStorageConfig } from '@/config/localstorage.config'

  const pkCorp = localStorage.getItem(localStorageConfig.__pkCorp)
  const $baseMessage = inject('$baseMessage')
  const dialogVisible = ref(false),
    dialogTitle = ref('增加计量单位'),
    formRef = ref(),
    form = reactive({}),
    rules = reactive({
      measCode: [
        { required: true, trigger: 'blur', message: '请输入单位编码' },
      ],
      measName: [
        { required: true, trigger: 'blur', message: '请输入单位名称' },
      ],
    })

  let baseRecord = ref(null)

  const openDialog = (record) => {
    dialogVisible.value = true
    if (record) {
      dialogTitle.value = '修改计量单位'
      baseRecord.value = record
      form['pkMeasdoc'] = record.pkMeasdoc ? record.pkMeasdoc : ''
      form['measCode'] = record.measCode ? record.measCode : ''
      form['measName'] = record.measName ? record.measName : ''
    } else {
      dialogTitle.value = '增加计量单位'
      form['measCode'] = ''
      form['measName'] = ''
      form['pkCorp'] = pkCorp
    }
  }
  const save = () => {
    if (!formRef.value) return
    formRef.value.validate(async (valid) => {
      if (valid) {
        let res = null
        if (baseRecord.value) {
          res = await updateMeasdocApi({
            pkWh: baseRecord.value.pkWh,
            ...form,
          })
        } else {
          res = await addMeasdocApi({
            ...form,
          })
        }
        if (res && res.code === 2000) {
          $baseMessage('操作成功', 'success')
          _emit('success-callback')
          closeDialog()
        } else {
          $baseMessage(res && res.msg ? res.msg : '操作失败,请重试', 'error')
        }
      } else {
        return false
      }
    })
  }
  const closeDialog = () => {
    baseRecord.value = null
    dialogVisible.value = false
  }
  defineExpose({ openDialog })
  const _emit = defineEmits(['success-callback'])
</script>
